package vip.xianz.jobmanager.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Constants;
import org.springframework.web.servlet.HandlerInterceptor;
import vip.xianz.jobmanager.data.vo.ResultBean;
import vip.xianz.jobmanager.util.ContextUtils;
import vip.xianz.jobmanager.util.SessionUtils;
import vip.xianz.jobmanager.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤，验证前台提交的验证消息
 *
 * @author xian5
 * @create 2019 -05 -07  15:49
 */
public class CaptchaInterceptor implements HandlerInterceptor {

    /**
     * 对存在验证码的请求，进行验证码验证
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String captcha = request.getParameter("captcha");
        if (StringUtils.notNull(captcha)) {
            String captchaSession = (String) SessionUtils.getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (StringUtils.notNull(captchaSession)) {
                if (!captcha.toUpperCase().equals(captchaSession)) {
                    // 验证码存在且不匹配
                    sendFailResponseData(response);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 发送失败验证的json数据回显给客户端
     * @param response
     */
    private void sendFailResponseData(HttpServletResponse response) {
        ResultBean<?> result = new ResultBean<>();
        result.setMsg(ContextUtils.getMessage("validate.captcha"));
        result.setCode(ResultBean.FAIL);
        String responseData = JSON.toJSONString(result);
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(responseData);
        } catch (IOException e) {
        }
    }
}
